<template>
  <div id="Plan">
    <a-row :gutter="16">
      <a-col :span="10" >
        <div class="card">
          <a-card title="业务规划" style="width: 100%;min-height: 75vh">
            <template #extra><a-button @click="planDemand" type="primary">规划业务</a-button></template>
            <template v-if="demandResList.length===0">
              <a-empty style="height: 100%;margin: auto 0">
                <a-button @click="planDemand" type="primary">规划业务</a-button>
              </a-empty>
            </template>
            <template v-else>
              <CollapsiblePanel :dataList="demandResList" :pageSize="8" />
            </template>

          </a-card>
        </div>
      </a-col>
      <a-col :span="14" >
        <div class="map">
          <DemandMap ></DemandMap>
        </div>

      </a-col>
    </a-row>
    <a-modal v-model:open="planOpen" title="规划业务" :footer="null">
      <a-form
          :model="planParams"
          name="basic"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
          autocomplete="off"
          @finish="handleDemandPlanOk"
      >
        <a-form-item
            label="层级"
            name="layer"
            :rules="[{ required: true, message: '请输入头节点名称!' }]"
        >
          <a-select
              ref="select"
              v-model:value="planParams.layer"
              style="width: 100%"

              :options="layerSelectList"/>
        </a-form-item>

        <a-form-item
            label="规划策略"
            name="strategy"
            :rules="[{ required: true, message: '请输入规划策略!' }]"
        >
          <a-select
              ref="select"
              v-model:value="planParams.strategy"
              style="width: 100%"
              :options="strategyList"/>
        </a-form-item>


        <a-form-item
            label="breakWeight"
            name="breakWeight"
            :rules="[{ required: planParams.strategy === 'KSP_DQN', message: '请输入breakWeight!' }]"
        >
          <a-input-number style="width: 100%" v-model:value="planParams.breakWeight" />
        </a-form-item>

        <a-form-item
            label="resourceWeight"
            name="resourceWeight"
            :rules="[{ required: planParams.strategy === 'KSP_DQN', message: '请输入resourceWeight!' }]"
        >
          <a-input-number style="width: 100%" v-model:value="planParams.resourceWeight" />
        </a-form-item>

        <a-form-item
            label="lengthWeight"
            name="lengthWeight"
            :rules="[{ required: planParams.strategy === 'KSP_DQN', message: '请输入lengthWeight!' }]"
        >
          <a-input-number style="width: 100%" v-model:value="planParams.lengthWeight" />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" html-type="submit">提交信息</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>

</template>

<script setup>
import Map from "@/components/Map.vue";
import CollapsiblePanel from "@/components/CollapsiblePanel.vue";
import {onMounted, ref} from "vue";
import useProject from "../store/project.js";
import {storeToRefs} from "pinia";
import {layerSelectList,strategyList} from './constantArr/SelectListConstant.js'
import useDemand from "../store/demand.js";
import DemandMap from "../components/DemandMap.vue";

const projectStore = useProject();
const{currentProject} = storeToRefs(projectStore);
const demandStore = useDemand();
const {planResult} = storeToRefs(demandStore);
const planOpen=ref(false)
const planParams=ref({
  projectName:currentProject.value.name,
  layer:'ALL',
  strategy:'HOP',
  breakWeight:1,
  resourceWeight:1,
  lengthWeight:1
})


const demandResList=ref([])
const workDemandList=ref([])
const protectDemandList=ref([])

//获取业务展示信息
const getDemandShowArr=()=>{
  return demandStore.workRouteList.map((item)=>{
    // 处理路由字符串的通用函数
    const processRouteString = (routes, startNode, endNode) => {
      if (!routes || !Array.isArray(routes) || routes.length === 0) {
        return '没有规划出路由';
      }

      // 如果只有一条路由，直接返回
      if (routes.length === 1) {
        return routes[0];
      }

      // 将路由转换为节点对
      const segments = routes.map(route => {
        const [node1, node2] = route.split('-');
        return [node1, node2];
      });

      // 构建路径
      let result = [];
      let current = startNode;
      let usedSegments = new Set();

      // 从起点开始构建路径
      while (current !== endNode && usedSegments.size < segments.length) {
        let found = false;
        for (let i = 0; i < segments.length; i++) {
          if (usedSegments.has(i)) continue;

          const [node1, node2] = segments[i];
          if (node1 === current) {
            result.push(current);
            current = node2;
            usedSegments.add(i);
            found = true;
            break;
          } else if (node2 === current) {
            result.push(current);
            current = node1;
            usedSegments.add(i);
            found = true;
            break;
          }
        }
        if (!found) break;
      }

      // 添加最后一个节点
      if (current === endNode) {
        result.push(endNode);
        return result.join('-');
      }

      // 如果无法构建完整路径，返回原始列表
      return routes.join(', ');
    };

    // 处理网络1的路由
    const net1WorkRoute = item.routeFibers?.length === 0 ? '没有规划出路由' : 
                         (item.routeFibers?.length === 1 ? item.routeFibers[0] : 
                         processRouteString(item.routeFibers, item.sourceNode.nodeName, item.targetNode.nodeName));

    const net1ProtectRoute = item.protectRouteFibers?.length === 0 ? '没有规划出路由' : 
                            (item.protectRouteFibers?.length === 1 ? item.protectRouteFibers[0] : 
                            processRouteString(item.protectRouteFibers, item.sourceNode.nodeName, item.targetNode.nodeName));

    // 处理网络2的路由
    const net2WorkRoute = item.doubleRouteFibers?.length === 0 ? '没有规划出路由' : 
                         (item.doubleRouteFibers?.length === 1 ? item.doubleRouteFibers[0] : 
                         processRouteString(item.doubleRouteFibers, item.sourceNode.nodeName + '2', item.targetNode.nodeName + '2'));

    const net2ProtectRoute = item.doubleProtectRouteFibers?.length === 0 ? '没有规划出路由' : 
                            (item.doubleProtectRouteFibers?.length === 1 ? item.doubleProtectRouteFibers[0] : 
                            processRouteString(item.doubleProtectRouteFibers, item.sourceNode.nodeName + '2', item.targetNode.nodeName + '2'));

    return{
      id:item.id,
      name:item.name,
      result:item.result,
      protect:item.protect,
      worRouteNodeList:item.workRoute,
      protectRouteNodeList:item.protectRoute,
      workRoute:net1WorkRoute,
      protectRoute:net1ProtectRoute,
      content:item.name+"-"+item.result,
      demandHead:item.demandHead,
      demandTail:item.demandTail,
      doubleRouteFibers: net2WorkRoute,
      doubleProtectRouteFibers: net2ProtectRoute
    }
  })
}

onMounted(()=>{
  let tempArr=[];
  demandResList.value=getDemandShowArr()
  // demandResList.value=tempArr
})

const planDemand = () => {
  planOpen.value=true
}
const handleDemandPlanOk = async () => {
  try {
    // 确保 projectName 是正确的
    console.log("当前项目名称：", currentProject.value.name);
    console.log("规划参数：", {
      projectName: planParams.value.projectName,
      layer: planParams.value.layer,
      strategy: planParams.value.strategy,
      breakWeight: planParams.value.breakWeight,
      resourceWeight: planParams.value.resourceWeight,
      lengthWeight: planParams.value.lengthWeight
    });

    // 1. 规划业务
    const planRes = await demandStore.planDemand(
      currentProject.value.name,  // 使用当前项目名称
      planParams.value.layer,
      planParams.value.strategy,
      planParams.value.breakWeight,
      planParams.value.resourceWeight,
      planParams.value.lengthWeight
    );
    
    if (!planRes) {
      throw new Error("规划失败：没有返回数据");
    }
    
    console.log("规划响应数据：", planRes);

    // 2. 重新获取业务列表
    await demandStore.getDemandList(currentProject.value.name);

    // 3. 获取工作路由
    const workRes = await demandStore.getWorkRoute(currentProject.value.name);
    console.log("工作路由响应：", workRes);
    
    // 4. 获取保护路由
    const protectRes = await demandStore.getProtectRoute(currentProject.value.name);
    console.log("保护路由响应：", protectRes);
    
    // 5. 检查 store 中的状态
    console.log("Store 中的状态：", {
      planResult: demandStore.planResult,
      workRoute: demandStore.workRoute,
      protectRoute: demandStore.protectRoute,
      demandList: demandStore.demandList,
      demandNameList: demandStore.demandNameList
    });
    
    // 6. 更新展示数据
    demandResList.value = getDemandShowArr();
    console.log("最终展示数据：", demandResList.value);
  } catch (error) {
    console.error("规划过程出错：", error);
  }
  planOpen.value = false;
};
</script>

<style scoped>
.card{
  background: rgba(236,236,236,0.5);
  padding: 10px;
  min-height: 75vh;
}
.map{
  min-height: 75vh;
  height: 100%;
  background: rgba(236,236,236,0.5);
  padding: 10px
}
</style>